# -*- coding:UTF-8 -*-

import logging
import time

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as expected
from selenium.webdriver.support.wait import WebDriverWait

logging.basicConfig(level=logging.INFO)


class SelenuimZt:
    def __init__(self, url, user, pwd, product, project, opt=1, all=1):
        if opt == '1':
            # 0 浏览器无头模式
            options = Options()
            options.add_argument('-headless')
            self.dr = webdriver.Chrome(chrome_options=options)
        else:
            # 正常启用浏览器界面
            self.dr = webdriver.Chrome()
        self.wait = WebDriverWait(self.dr, timeout=5)
        self.loginUrl, self.user, self.password, self.product, self.project, self.all = url, user, pwd, product, project, all
        self._login()

    def _login(self):
        """
        登录
        :return:
        """
        self.dr.get(self.loginUrl)
        self.wait.until(expected.visibility_of_element_located((By.ID, "account")))
        self.dr.find_element_by_id("account").click()
        self.dr.find_element_by_id("account").send_keys(self.user)
        self.dr.find_element_by_name("password").click()
        self.dr.find_element_by_name("password").send_keys(self.password)
        self.dr.find_element_by_id("submit").click()

    # def enter_project(self):    #这个可用，但已经遗弃
    #     """
    #     进入指定的项目，获取项目任务列表
    #     :return:
    #     """
    #     try:
    #         self.dr.find_element_by_xpath("//nav[@id='navbar']/ul/li[@data-id='project']").click()  # 点击项目1级菜单
    #         self.wait.until(expected.visibility_of_element_located((By.ID, "currentItem")))  # 等到项目选择框 可见
    #         self.dr.find_element_by_id("currentItem").click()
    #         self.dr.find_element_by_xpath("//*[@id='dropMenu']/div[1]/input").send_keys(self.project)  # 项目搜索框中输入指定项目名称
    #         time.sleep(0.5)
    #         self.dr.find_element_by_xpath(
    #             "//div[@id='dropMenu']/div[2]//a[@title='{}']".format(self.project)).click()  # 选择指定的项目
    #         time.sleep(0.5)
    #         if self.all == 1:
    #             self.dr.find_element_by_id('assignedtome').click()
    #             time.sleep(0.2)
    #         try:
    #             # 如果项目任务列表表头展示，往下执行。如果报错，说明任务列表为空，则直接返回 【0,0】列表
    #             if self.dr.find_element_by_xpath("//*[@id='taskList']/thead/tr").is_displayed():
    #                 pass
    #         except BaseException as e:
    #             return [0, 0]
    #         self.wait.until(expected.visibility_of_element_located((By.XPATH, "//*[@id='taskList']/thead/tr")))
    #         theadth = self.dr.find_elements_by_xpath("//*[@id='taskList']/thead/tr/th")  # 任务列表 列数
    #         theadtext = []
    #         for t in range(len(theadth)):
    #             # 获取任务列表 表头的title文字
    #             theadtext.append(
    #                 self.dr.find_element_by_xpath("//*[@id='taskList']/thead/tr/th[{}]".format(t + 1)).get_attribute(
    #                     "title"))
    #         logging.info("未关闭任务列表，表头为：{}".format(theadtext))
    #         bodydrs = self.dr.find_elements_by_xpath("//*[@id='taskList']/tbody/tr")  # 任务列表 行数
    #         dictstatus = {"未开始": 0, "进行中": 0, "已完成": 0, "已暂停": 0, "已取消": 0, "已关闭": 0}  # 初始化任务各状态数量为0
    #         tasklist = []
    #         for d in range(len(bodydrs)):
    #             task = []
    #             # theadtext.index(**),这样能准确获得列的序号
    #             status = self.dr.find_element_by_xpath(
    #                 "//*[@id='taskList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index("状态") + 1)).text
    #             task.append(status)
    #             Id = self.dr.find_element_by_xpath(
    #                 "//*[@id='taskList']/tbody/tr[{}]/td[{}]/a".format(d + 1, theadtext.index('ID') + 1)).text
    #             task.append("Task-" + str(Id))
    #             # 指派给
    #             assignedTo = self.dr.find_element_by_xpath(
    #                 "//*[@id='taskList']/tbody/tr[{}]/td[{}]//span".format(d + 1, theadtext.index('指派给') + 1)).text
    #             task.append(assignedTo)
    #             pri = self.dr.find_element_by_xpath(
    #                 "//*[@id='taskList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index('P') + 1)).text + "级"
    #             task.append(pri)
    #             # jd = self.dr.find_element_by_xpath(
    #             #     "//*[@id='taskList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index('进度') + 1)).text
    #             # task.append(jd)
    #             name = self.dr.find_element_by_xpath(
    #                 "//*[@id='taskList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index("任务名称") + 1)).text
    #             task.append(name)
    #             deadline = '2019-' + self.dr.find_element_by_xpath(
    #                 "//*[@id='taskList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index("截止") + 1)).text
    #             task.append(deadline)
    #             tasklist.append(task)
    #             dictstatus[status.strip()] += 1
    #         logging.info("未关闭的任务中 任务最多有{}条".format(max(dictstatus.values())))
    #         logging.info("任务列表为：{}".format(tasklist))
    #         return max(dictstatus.values()), tasklist
    #     except BaseException as e:
    #         logging.error(e)
    #     # finally:
    #     #     self.dr.close()

    # def get_story(self):    #这个可用，已被遗弃
    #     """
    #     进入指定的项目，获取项目任务列表
    #     :return:
    #     """
    #     try:
    #         self.dr.find_element_by_xpath("//nav[@id='navbar']/ul/li[@data-id='product']").click()  # 点击项目1级菜单
    #         self.wait.until(expected.visibility_of_element_located((By.ID, "currentItem")))  # 等到项目选择框 可见
    #         self.dr.find_element_by_id("currentItem").click()
    #         self.dr.find_element_by_xpath("//*[@id='dropMenu']/div[1]/input").send_keys(self.product)  # 项目搜索框中输入指定项目名称
    #         time.sleep(0.5)
    #         self.dr.find_element_by_xpath(
    #             "//div[@id='dropMenu']/div[2]//a[@title='{}']".format(self.product)).click()  # 选择指定的项目
    #         time.sleep(0.5)
    #         if self.all == 1:
    #             self.dr.find_element_by_id('assignedtomeTab').click()
    #             time.sleep(0.2)
    #         try:
    #             # 如果项目任务列表表头展示，往下执行。如果报错，说明任务列表为空，则直接返回 【0,0】列表
    #             if self.dr.find_element_by_xpath("//*[@id='storyList']/thead/tr").is_displayed():
    #                 pass
    #         except BaseException as e:
    #             return [0, 0]
    #         self.wait.until(expected.visibility_of_element_located((By.XPATH, "//*[@id='storyList']/thead/tr")))
    #         theadth = self.dr.find_elements_by_xpath("//*[@id='storyList']/thead/tr/th")  # 任务列表 列数
    #         theadtext = []
    #         for t in range(len(theadth)):
    #             # 获取任务列表 表头的title文字
    #             theadtext.append(
    #                 self.dr.find_element_by_xpath("//*[@id='storyList']/thead/tr/th[{}]".format(t + 1)).get_attribute(
    #                     "title"))
    #         logging.info("未关闭任务列表，表头为：{}".format(theadtext))
    #         bodydrs = self.dr.find_elements_by_xpath("//*[@id='storyList']/tbody/tr")  # 任务列表 行数
    #         dictstatus = {"未开始": 0, "进行中": 0, "已完成": 0, "已暂停": 0, "已取消": 0, "已关闭": 0}  # 初始化任务各状态数量为0
    #         storylist = []
    #         for d in range(len(bodydrs)):
    #             story = []
    #             # theadtext.index(**),这样能准确获得列的序号
    #             status = self.dr.find_element_by_xpath(
    #                 "//*[@id='storyList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index("状态") + 1)).text
    #             story.append('进行中' if status == '激活' else '未开始')
    #             Id = self.dr.find_element_by_xpath(
    #                 "//*[@id='storyList']/tbody/tr[{}]/td[{}]/a".format(d + 1, theadtext.index('ID') + 1)).text
    #             story.append("Story-" + str(Id))
    #             # 指派给
    #             assignedTo = self.dr.find_element_by_xpath(
    #                 "//*[@id='storyList']/tbody/tr[{}]/td[{}]//span".format(d + 1, theadtext.index('指派') + 1)).text
    #             story.append(assignedTo)
    #             pri = self.dr.find_element_by_xpath(
    #                 "//*[@id='storyList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index('P') + 1)).text + "级"
    #             story.append(pri)
    #             # jd = self.dr.find_element_by_xpath(
    #             #     "//*[@id='storyList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index('进度') + 1)).text
    #             # task.append(jd)
    #             name = self.dr.find_element_by_xpath(
    #                 "//*[@id='storyList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index("任务名称") + 1)).text
    #             story.append(name)
    #             # deadline = self.dr.find_element_by_xpath(
    #             #     "//*[@id='storyList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index("阶段") + 1)).text
    #             story.append('0000-00-00')
    #             storylist.append(story)
    #             dictstatus['进行中' if status == '激活' else '未开始'] += 1
    #         logging.info("未关闭的任务中 任务最多有{}条".format(max(dictstatus.values())))
    #         logging.info("任务列表为：{}".format(storylist))
    #         return max(dictstatus.values()), storylist
    #     except BaseException as e:
    #         logging.error(e)

    # def get_bug(self):        #这个还没有写好，还有问题
    #     """
    #     进入指定的项目，获取项目任务列表
    #     :return:
    #     """
    #     try:
    #         self.dr.find_element_by_xpath("//nav[@id='navbar']/ul/li[@data-id='qa']").click()  # 点击项目1级菜单
    #         self.wait.until(expected.visibility_of_element_located((By.ID, "currentItem")))  # 等到项目选择框 可见
    #         self.dr.find_element_by_id("currentItem").click()
    #         self.dr.find_element_by_xpath("//*[@id='dropMenu']/div[1]/input").send_keys(self.product)  # 项目搜索框中输入指定项目名称
    #         time.sleep(0.5)
    #         self.dr.find_element_by_xpath(
    #             "//div[@id='dropMenu']/div[2]//a[@title='{}']".format(self.product)).click()  # 选择指定的项目
    #         time.sleep(0.5)
    #         if self.all == 1:
    #             self.dr.find_element_by_xpath('//*[@id="mainMenu"]/div[2]/a[3]').click()
    #             time.sleep(0.2)
    #         try:
    #             # 如果项目任务列表表头展示，往下执行。如果报错，说明任务列表为空，则直接返回 【0,0】列表
    #             if self.dr.find_element_by_xpath("//*[@id='datatable-bugList']//table/thead/tr").is_displayed():
    #                 pass
    #         except BaseException as e:
    #             return [0, 0]
    #         self.wait.until(
    #             expected.visibility_of_element_located((By.XPATH, "//*[@id='datatable-bugList']//table/thead/tr")))
    #         # theadth = self.dr.find_elements_by_xpath("//*[@id='datatable-bugList']//table/thead/tr/th")  # 任务列表 列数
    #         # print(len(theadth))
    #         # theadtext = []
    #         # for t in range(len(theadth)-1):
    #         #     获取任务列表 表头的title文字
    #         #     theadtext.append(
    #         #         self.dr.find_element_by_xpath(
    #         #             "//*[@id='datatable-bugList']//table/thead/tr/th[{}]".format(t + 1)).get_attribute(
    #         #             "title"))
    #         # print(theadtext)
    #         # logging.info("未关闭任务列表，表头为：{}".format(theadtext))
    #         bodydrs = self.dr.find_elements_by_xpath("//*[@id='datatable-bugList']//table/tbody/tr")  # 任务列表 行数
    #         print(len(bodydrs))
    #         dictstatus = {"未开始": 0, "进行中": 0, "已完成": 0, "已暂停": 0, "已取消": 0, "已关闭": 0}  # 初始化任务各状态数量为0
    #         buglist = []
    #         for d in range(len(bodydrs)):
    #             bug = []
    #             # theadtext.index(**),这样能准确获得列的序号
    #             status = self.dr.find_element_by_xpath(
    #                 "//*[@id='datatable-bugList']//table[5]/tbody/tr[{}]/td[1]".format(d + 1)).__getattribute__('title')
    #             bug.append('进行中' if status == '激活' else '未开始')
    #             Id = self.dr.find_element_by_xpath(
    #                 "//*[@id='datatable-bugList']//table/tbody[4]/tr[{}]/td[1]/a".format(d + 1)).text
    #             bug.append("Bug-" + str(Id))
    #             # 指派给
    #             assignedTo = self.dr.find_element_by_xpath(
    #                 "//*[@id='datatable-bugList']//table/tbody[5]/tr[{}]/td[4]/a/span".format(d + 1)).text
    #             bug.append(assignedTo)
    #             pri = self.dr.find_element_by_xpath(
    #                 "//*[@id='datatable-bugList']//table/tbody[4]/tr[{}]/td[3]/span".format(d + 1)).text + "级"
    #             bug.append(pri)
    #             # jd = self.dr.find_element_by_xpath(
    #             #     "//*[@id='bugList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index('进度') + 1)).text
    #             # task.append(jd)
    #             name = self.dr.find_element_by_xpath(
    #                 "//*[@id='datatable-bugList']//table/tbody[4]/tr[{}]/td[4]/a".format(d + 1)).text
    #             bug.append(name)
    #             # deadline = '2019-' + self.dr.find_element_by_xpath(
    #             #     "//*[@id='bugList']/tbody/tr[{}]/td[{}]".format(d + 1, theadtext.index("截止") + 1)).text
    #             bug.append("0000-00-00")
    #             buglist.append(bug)
    #             dictstatus['进行中' if status == '激活' else '未开始'] += 1
    #         logging.info("未关闭的任务中 任务最多有{}条".format(max(dictstatus.values())))
    #         logging.info("任务列表为：{}".format(buglist))
    #         return max(dictstatus.values()), buglist
    #     except BaseException as e:
    #         logging.error(e)

    def user_site_data(self):
        try:
            self.wait.until(
                expected.visibility_of_element_located((By.XPATH, '//*[@id="subNavbar"]/ul/li[@data-id="index"]')))
            dictvalue = {}
            taskdata = self._user_site_taskdata()
            bugdata = self._user_site_bugdata()
            storydata = self._user_site_storydata()
            dictvalue['taskdata'] = taskdata[1] if taskdata[1] else 0
            dictvalue['bugdata'] = bugdata[1] if bugdata[1] else 0
            dictvalue['storydata'] = storydata[1] if storydata[1] else 0
            taskstatus = {}
            if taskdata[0] != 0:
                taskstatus[taskdata[0][0]] = taskdata[0][1]
            bugstatus = {}
            if bugdata[0] != 0:
                bugstatus[bugdata[0][0]] = bugdata[0][1]
            storystatus = {}
            if storydata[0] != 0:
                storystatus[storydata[0][0]] = storydata[0][1]
            for st in [taskstatus, bugstatus]:
                if st:
                    for k, v in st.items():
                        storystatus[k] += v
            return max(storystatus.values()) if storystatus else 0, dictvalue
        except BaseException as e:
            logging.error(e)

    def _user_site_taskdata(self):
        # 获取 任务 中指派给我 的数据
        self.dr.find_element_by_xpath('//*[@id="subNavbar"]/ul/li[@data-id="task"]').click()  # 点击二级菜单
        time.sleep(0.2)
        try:
            if self.dr.find_element_by_xpath('//*[@id="tasktable"]/thead/tr').is_displayed():
                ths = self.dr.find_elements_by_xpath('//*[@id="tasktable"]/thead/tr/th')
                thtexts = []
                for t in range(len(ths)):
                    thtexts.append(self.dr.find_element_by_xpath(
                        '//*[@id="tasktable"]/thead/tr/th[{}]'.format(t + 1)).get_attribute('title'))
                tbodytr = self.dr.find_elements_by_xpath('//*[@id="tasktable"]/tbody/tr')
                tasklist = []
                dictstatus = {"未开始": 0, "进行中": 0, "已完成": 0, "已暂停": 0, "已取消": 0, "已关闭": 0}  # 初始化任务各状态数量为0
                for tr in range(len(tbodytr)):
                    task = []
                    status = self.dr.find_element_by_xpath(
                        '//*[@id="tasktable"]/tbody/tr[{}]/td[{}]/span'.format(tr + 1, thtexts.index(
                            '状态') + 1)).text.strip()
                    task.append(status)
                    dictstatus[status] += 1
                    task.append('Task-' + self.dr.find_element_by_xpath(
                        '//*[@id="tasktable"]/tbody/tr[{}]/td[{}]'.format(tr + 1, thtexts.index('ID') + 1)).text)
                    task.append(self.dr.find_element_by_xpath(
                        '//*[@id="tasktable"]/tbody/tr[{}]/td[{}]/a/span'.format(tr + 1,
                                                                                 thtexts.index('指派给') + 1)).text)
                    task.append(self.dr.find_element_by_xpath(
                        '//*[@id="tasktable"]/tbody/tr[{}]/td[{}]/span'.format(tr + 1,
                                                                               thtexts.index('P') + 1)).text + '级')
                    task.append(self.dr.find_element_by_xpath(
                        '//*[@id="tasktable"]/tbody/tr[{}]/td[{}]/a'.format(tr + 1,
                                                                            thtexts.index('任务名称') + 1)).text)
                    deadline = self.dr.find_element_by_xpath(
                        '//*[@id="tasktable"]/tbody/tr[{}]/td[{}]'.format(tr + 1, thtexts.index('截止') + 1)).text
                    task.append(deadline if deadline else '0000-00-00')
                    tasklist.append(task)
                return [max(dictstatus.items()), tasklist]
        except BaseException as e:
            return [0, 0]

    def _user_site_bugdata(self):
        # 获取 任务 中指派给我 的数据
        self.dr.find_element_by_xpath('//*[@id="subNavbar"]/ul/li[@data-id="bug"]').click()  # 点击二级菜单
        time.sleep(0.2)
        try:
            if self.dr.find_element_by_xpath('//*[@id="bugList"]/thead/tr').is_displayed():
                ths = self.dr.find_elements_by_xpath('//*[@id="bugList"]/thead/tr/th')
                thtexts = []
                for t in range(len(ths)):
                    thtexts.append(self.dr.find_element_by_xpath(
                        '//*[@id="bugList"]/thead/tr/th[{}]'.format(t + 1)).get_attribute('title'))
                tbodytr = self.dr.find_elements_by_xpath('//*[@id="bugList"]/tbody/tr')
                buglist = []
                dictstatus = {"未开始": 0, "进行中": 0, "已完成": 0, "已暂停": 0, "已取消": 0, "已关闭": 0}  # 初始化任务各状态数量为0
                for tr in range(len(tbodytr)):
                    bug = []
                    bug.append("进行中")
                    dictstatus['进行中'] += 1
                    bug.append('Bug-' + self.dr.find_element_by_xpath(
                        '//*[@id="bugList"]/tbody/tr[{}]/td[{}]'.format(tr + 1, thtexts.index('ID') + 1)).text)
                    bug.append(self.dr.find_element_by_xpath(
                        '//*[@id="bugList"]/tbody/tr[{}]/td[{}]'.format(tr + 1, thtexts.index('类型') + 1)).text)
                    bug.append(self.dr.find_element_by_xpath(
                        '//*[@id="bugList"]/tbody/tr[{}]/td[{}]/span'.format(tr + 1,
                                                                             thtexts.index('P') + 1)).text + '级')
                    bug.append(self.dr.find_element_by_xpath(
                        '//*[@id="bugList"]/tbody/tr[{}]/td[{}]/a'.format(tr + 1,
                                                                          thtexts.index('Bug标题') + 1)).text)
                    bug.append("0000-00-00")
                    buglist.append(bug)
                return [max(dictstatus.items()), buglist]
        except BaseException as e:
            return [0, 0]

    def _user_site_storydata(self):
        # 获取 任务 中指派给我 的数据
        self.dr.find_element_by_xpath('//*[@id="subNavbar"]/ul/li[@data-id="story"]').click()  # 点击二级菜单
        time.sleep(0.2)
        try:
            if self.dr.find_element_by_xpath('//*[@id="myStoryForm"]/table/thead/tr').is_displayed():
                ths = self.dr.find_elements_by_xpath('//*[@id="myStoryForm"]/table/thead/tr/th')
                thtexts = []
                for t in range(len(ths)):
                    thtexts.append(self.dr.find_element_by_xpath(
                        '//*[@id="myStoryForm"]/table/thead/tr/th[{}]'.format(t + 1)).get_attribute('title'))
                tbodytr = self.dr.find_elements_by_xpath('//*[@id="myStoryForm"]/table/tbody/tr')
                storylist = []
                dictstatus = {"未开始": 0, "进行中": 0, "已完成": 0, "已暂停": 0, "已取消": 0, "已关闭": 0}  # 初始化任务各状态数量为0
                for tr in range(len(tbodytr)):
                    story = []
                    story.append("进行中")
                    dictstatus['进行中'] += 1
                    story.append('Bug-' + self.dr.find_element_by_xpath(
                        '//*[@id="myStoryForm"]/table/tbody/tr[{}]/td[{}]'.format(tr + 1,
                                                                                  thtexts.index('ID') + 1)).text)
                    story.append(self.dr.find_element_by_xpath(
                        '//*[@id="myStoryForm"]/table/tbody/tr[{}]/td[{}]'.format(tr + 1,
                                                                                  thtexts.index('阶段') + 1)).text)
                    story.append(self.dr.find_element_by_xpath(
                        '//*[@id="myStoryForm"]/table/tbody/tr[{}]/td[{}]/span'.format(tr + 1,
                                                                                       thtexts.index(
                                                                                           'P') + 1)).text + '级')
                    story.append(self.dr.find_element_by_xpath(
                        '//*[@id="myStoryForm"]/table/tbody/tr[{}]/td[{}]/a'.format(tr + 1,
                                                                                    thtexts.index('需求名称') + 1)).text)
                    story.append("0000-00-00")
                    storylist.append(story)
                return [max(dictstatus.items()), storylist]
        except BaseException as e:
            return [0, 0]
